const Service = require('egg').Service;

class BlogsService extends Service {
  async add() {
    const { app, ctx } = this;
    const { title, content, author } = ctx.request.body;
    const isData = await app.mysql.get('blogs', {
      title
    })
    if (!isData) {
      const data = await app.mysql.insert('blogs', {
        title, content, author
      })
      if (data.affectedRows) {
        return { code: 0, msg: '添加成功', id: data.insertId }
      } else {
        return { code: -1, msg: '添加失败' }
      }
    } else {
      return { code: -1, msg: '标题重复了' }
    }

  }

  async delete() {
    const { app, ctx } = this;
    const { id } = ctx.query; // ：id

    const deleteRes = await app.mysql.get('blogs', { id })
    console.log(deleteRes, 'id----id')
    if (!deleteRes) {
      return { code: -1, msg: '当前id不存在' }
    }
    const result = await app.mysql.delete('blogs', { id });
    console.log('result:', result, 'result')
    if (result.affectedRows) {
      return { code: 0, msg: '删除成功', id: result.insertId }
    } else {
      return { code: -1, msg: '删除失败' }
    }
  }
  async deleteAll() {
    // 
    const { app, ctx } = this;
    const { ids } = ctx.request.body;
    const data = await app.mysql.query(`delete from blogs where id in (${ids})`);
    if (data.affectedRows) {
      return { code: 0, msg: '删除成功', data }
    } else {
      return { code: 0, msg: '删除失败' }
    }
  }
  async update() {
    const { id } = this.ctx.params
    const result = await this.app.mysql.update('blogs', { id, ...this.ctx.request.body }); // 更新 posts 表中的记录
    if (result.affectedRows) {
      return { code: 0, msg: '更新成功', data: result }
    } else {
      return { code: -1, msg: '更新失败' }
    }
  }

  async findAll() {
    const result = await this.app.mysql.select('blogs');
    return { code: 0, msg: '查询成功', data: result }
  }
  async search() {
    const { app } = this;
  }
  async page() {
    const { page, size } = this.ctx.query
    const num = await this.app.mysql.select('blogs');
    const results = await this.app.mysql.select('blogs', { // 搜索 post 表
      orders: [['id', 'desc']], // 排序方式
      limit: size * 1, // 返回数据量
      offset: page * size * 1, // 数据偏移量
    });
    return { code: 0, msg: '查询成功', data: results, total: num.length }
  }
}

module.exports = BlogsService;